package com.kevinpascoe.apps.loneworker;

import java.util.Timer;
import java.util.TimerTask;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.NumericWheelAdapter;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class LoneWorkerActivity extends Activity implements SensorEventListener {

	Integer count = 0;
	// Wheel scrolled flag
	Integer intHours = 0;
	Integer intMins = 0;
	Integer intSecs = 0;
	
	Integer storedIntHours = 0;
	Integer storedIntMins = 0;
	Integer storedIntSecs = 0;
	
	long elapsed;
	
	Boolean StopPressed = false;
	Boolean PhoneMoved = false;
	
	private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    



	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		PreferenceManager.setDefaultValues(this, R.xml.settings, false);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
		final String mine = prefs.getString("txtNumber", "hello");
	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		TextView tv = (TextView) findViewById(R.id.textView1);
		tv.setText(mine.toString());

		initNumberWheel(R.id.hour,24);
		initNumberWheel(R.id.mins,60);
		initNumberWheel(R.id.secs,60);

		Button but = (Button) findViewById(R.id.start);
		but.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				count = ((intHours*60*60)+(intMins*60)+intSecs)*1000;
				WheelView wheel;
				wheel = (WheelView) findViewById(R.id.hour);
				wheel.setEnabled(false);
				wheel = (WheelView) findViewById(R.id.mins);
				wheel.setEnabled(false);
				wheel = (WheelView) findViewById(R.id.secs);
				wheel.setEnabled(false);
				
				disableStartButton();
				enableStopButton();
				
				storedIntHours = intHours;
				storedIntMins = intMins;
				storedIntSecs = intSecs;

				
				TimerTask task = new TimerTask(){

					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						elapsed += 1000;
						if(StopPressed || PhoneMoved || elapsed >= count) {	
							enableStartButton();
							disableStopButton();
							intSecs = storedIntSecs;
							intHours = storedIntHours;
							intMins = storedIntMins;
							enable_wheels();
							update_wheels_and_set_text("Finished");
							this.cancel();
							//Only send SMS if we timed out
							if(!StopPressed && !PhoneMoved) {
								sendSMS("","Test");
							}
							StopPressed = false;
							PhoneMoved = false;
							elapsed = 0;

							return;
						}

						Integer num = (int) elapsed;
						
						
						intSecs--;
						if(intSecs < 0){
							intSecs = 59;
							intMins--;
							if(intMins < 0){
								intMins = 59;
								intHours--;
							}
						}
						

						update_wheels_and_set_text(num.toString());
					}
					
				};
				Timer timer = new Timer();
		        timer.scheduleAtFixedRate(task, 1000, 1000);
		        
				
			}
		});
		
		but = (Button) findViewById(R.id.stop);
		but.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				StopPressed = true;
			}
		});
		
		 mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
         mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	}
	
	private void enableStartButton() {
		this.runOnUiThread(new Runnable(){

			public void run() {
				Button but = (Button) findViewById(R.id.start);
				but.setEnabled(true);
			}
			
		});
	}
	
	private void disableStartButton() {
		this.runOnUiThread(new Runnable(){

			public void run() {
				Button but = (Button) findViewById(R.id.start);
				but.setEnabled(false);
			}
			
		});
	}
	
	private void enableStopButton() {
		this.runOnUiThread(new Runnable(){

			public void run() {
				Button but = (Button) findViewById(R.id.stop);
				but.setEnabled(true);
			}
			
		});
	}
	
	private void disableStopButton() {
		this.runOnUiThread(new Runnable(){

			public void run() {
				Button but = (Button) findViewById(R.id.stop);
				but.setEnabled(false);
			}
			
		});
	}
	
	public void update_wheels_and_set_text(final String txt) {
		this.runOnUiThread(new Runnable(){

			public void run() {
				TextView tv = (TextView) findViewById(R.id.textView1);
				WheelView wheel;
				wheel = (WheelView) findViewById(R.id.hour);
				wheel.setCurrentItem(intHours);
				wheel = (WheelView) findViewById(R.id.mins);
				wheel.setCurrentItem(intMins);
				wheel = (WheelView) findViewById(R.id.secs);
				wheel.setCurrentItem(intSecs);
				//tv.setText(txt);
				
			}
		});
	}
	
	public void enable_wheels() {
		this.runOnUiThread(new Runnable(){

			public void run() {
				WheelView wheel;
				wheel = (WheelView) findViewById(R.id.hour);
				wheel.setEnabled(true);
				wheel = (WheelView) findViewById(R.id.mins);
				wheel.setEnabled(true);
				wheel = (WheelView) findViewById(R.id.secs);
				wheel.setEnabled(true);
				
			}
			
		});
		
	}
	
	public void update_txt(final String txt){
		this.runOnUiThread(new Runnable(){

			public void run() {
				TextView tv = (TextView) findViewById(R.id.textView1);
				tv.setText(txt);
			}
			
		});
	}

	// Wheel changed listener
	private final OnWheelChangedListener changedListener = new OnWheelChangedListener()
	{
		public void onChanged(WheelView wheel, int oldValue, int newValue)
		{
			if(wheel == (WheelView) findViewById(R.id.hour)){
				intHours = wheel.getCurrentItem();
			}

			if(wheel == (WheelView) findViewById(R.id.mins)){
				intMins = wheel.getCurrentItem();
			}

			if(wheel == (WheelView) findViewById(R.id.secs)){
				intSecs = wheel.getCurrentItem();
			}
		}

	};

	/**
	 * Initializes wheel
	 * 
	 * @param id
	 *          the wheel widget Id
	 */

	private void initNumberWheel(int id, int max_num)
	{
		WheelView wheel = (WheelView) findViewById(id);
		NumericWheelAdapter wheelAdapter = new NumericWheelAdapter(this,0,max_num,"%02d");
		wheelAdapter.setTextSize(50);
		wheel.setViewAdapter(wheelAdapter);
		wheel.setVisibleItems(2);
		wheel.setCurrentItem(0);
		wheel.setCyclic(true);
		wheel.addChangingListener(changedListener);
	}

	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	public void onSensorChanged(SensorEvent arg0) {
		// TODO Auto-generated method stub
		Integer x = (int)arg0.values[0];
		Integer y = (int)arg0.values[1];
		Integer z = (int)arg0.values[2];
		
		if( elapsed > 3000){
			if(x > 13 || x < -13){
				PhoneMoved=true;
			}
			if(y > 13 || y < -13){
				PhoneMoved=true;
			}
			if(z > 13 || z < -13){
				PhoneMoved=true;
			}
		}
		
		//update_txt(x.toString() + " - " + y.toString() + " - " + z.toString());
		
		

	}
	
	 protected void onResume() {
         super.onResume();
         mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
     }

     protected void onPause() {
         super.onPause();
         mSensorManager.unregisterListener(this);
     }
     
     //---sends an SMS message to another device---
     private void sendSMS(String phoneNumber, String message)
     {        
         PendingIntent pi = PendingIntent.getActivity(this, 0,
             new Intent(this, LoneWorkerActivity.class), 0);                
         SmsManager sms = SmsManager.getDefault();
         sms.sendTextMessage(phoneNumber, null, message, pi, null);        
     }    

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.menu, menu);
         return true;
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         // Handle item selection
         switch (item.getItemId()) {
             case R.id.settings:
            	 startActivity(new Intent(this, LoneWorkerSettings.class));
                 return(true);
 
             case R.id.about:
            	 LoneWorkerAbout about = new LoneWorkerAbout(this);
            	 about.setTitle("About");
            	 about.show();
                 return true;
             default:
                 return super.onOptionsItemSelected(item);
         }
     }
     
     @Override
     public void onActivityResult(int reqCode, int resultCode, Intent data) {
       super.onActivityResult(reqCode, resultCode, data);

       switch (reqCode) {
         case (123456) :
           if (resultCode == Activity.RESULT_OK) {
             Uri contactData = data.getData();
             Cursor c =  managedQuery(contactData, null, null, null, null);
             if (c.moveToFirst()) {
               String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
               update_txt(name);
               // TODO Whatever you want to do with the selected contact name.
               
             }
           }
           break;
       }
     }
}